package endpoint

import (
	"fmt"

	"github.com/infraboard/mcube/pb/resource"
)

func (s *EndpointSpecSet) Service() (svcs []string) {
	var m = map[string]int{}
	for i := range s.Items {
		item := s.Items[i]
		m[item.Service]++
	}

	for k := range m {
		svcs = append(svcs, k)
	}

	return
}

func NewEndpointSet(specs *EndpointSpecSet) *EndpointSet {
	set := &EndpointSet{
		Items: []*Endpoint{},
	}

	for i := range specs.Items {
		spec := specs.Items[i]
		set.Add(NewEndpoint(spec))
	}

	return set
}

func (s *EndpointSet) Add(items ...*Endpoint) {
	s.Items = append(s.Items, items...)
}

func (s *EndpointSet) ToMongoDocs() (docs []interface{}) {
	for i := range s.Items {
		docs = append(docs, s.Items[i])
	}
	return
}

func NewEndpoint(spec *EndpointSpec) *Endpoint {
	m := resource.NewMeta()

	// 补充Id
	m.Id = spec.GenId()
	return &Endpoint{
		Meta: m,
		Spec: spec,
	}
}

func NewEndpointSpecSet() *EndpointSpecSet {
	return &EndpointSpecSet{
		Items: []*EndpointSpec{},
	}
}

func (s *EndpointSpecSet) Add(items ...*EndpointSpec) {
	s.Items = append(s.Items, items...)
}

func NewEndpointSpec(service, path string) *EndpointSpec {
	return &EndpointSpec{
		Service: service,
		Path:    path,
	}
}

// Role需要应用Endpoint的Id, Endpint的Id不能随机生成
func (s *EndpointSpec) GenId() string {
	return fmt.Sprintf("%s.%s", s.Service, s.Path)
}

func GetValueFromMeta(meta map[string]interface{}, key string) string {
	v := meta[key]
	if v == nil {
		return ""
	}

	return v.(string)
}
